import { Component, Optional, Inject, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';

import { _HttpClient } from '@delon/theme';
import { ReuseTabService } from '@delon/abc';
import { DA_SERVICE_TOKEN, TokenService, SocialService } from '@delon/auth';

import { StartupService } from '@core';
import { HttpHeaders } from '@angular/common/http';
import { encryption, randomLenNum, openWindow, getQueryString } from '@shared';

const BIG_IMAGES = [
  `assets/img-big/bg5.jpeg`,
  `assets/img-big/bg6.jpeg`,
  `assets/img-big/bg7.jpeg`,
  `assets/img-big/bg1.jpg`,
  `assets/img-big/bg2.jpg`,
];

@Component({
  selector: 'account-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  host: {
    '[style.background-image]': `'url(' + bigImage + ')'`,
  },
  providers: [SocialService],
})
export class LoginComponent implements OnInit {
  // tslint:disable-next-line: no-bitwise
  bigImage = BIG_IMAGES[(Math.random() * BIG_IMAGES.length) | 0];
  loading = false;
  type = 'user';
  error = '';
  form: FormGroup;
  form2: FormGroup;
  codeUrl = '';

  header = new HttpHeaders({
    tenant_id: '1',
    Authorization: 'Basic Y2Y6Y2xvdWQtZnJhbWV3b3Jr',
  });

  constructor(
    fb: FormBuilder,
    private router: Router,
    private msg: NzMessageService,
    public http: _HttpClient,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private startupSrv: StartupService,
    private socialService: SocialService,
  ) {
    this.form = fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      code: [null, [Validators.required]],
      randomStr: [null, [Validators.required]],
    });
    this.form2 = fb.group({
      mobile: [null, [Validators.required]],
      captcha: [null, [Validators.required]],
    });
  }

  get mobile() {
    return this.form2.controls.mobile;
  }

  get captcha() {
    return this.form2.controls.captcha;
  }

  get password() {
    return this.form.controls.password;
  }

  get username() {
    return this.form.controls.username;
  }

  get code() {
    return this.form.controls.code;
  }

  t() {
    const appId = 'dingoau3hvign0r6uosxbj';
    const redirect_uri = encodeURIComponent(window.location.origin + window.location.pathname + '/#/account/authredirect');
    const url = `https://oapi.dingtalk.com/connect/qrconnect?appid=${appId}&response_type=code&scope=snsapi_login&state=DD-LOGIN&redirect_uri=${redirect_uri}`;
    this.socialService
      .login(url, '/', {
        type: 'window',
      })
      .subscribe(res => {
        const code = res.token;
        const state = res.state;
        // third回调登录
        if (state && code) {
          const grant_type = 'mobile';
          const params = {
            mobile: `${state}@${code}`,
            grant_type,
          };

          this.loading = true;
          this.http
            .post(`/cf/auth/mobile/token/social?_allow_anonymous=true`, null, params, {
              headers: this.header,
            })
            .subscribe(
              this.loginCallBack,
              err => {
                this.loading = false;
                this.refreshCode();
              },
              () => {
                this.loading = false;
              },
            );
        }
      });
  }

  /**
   * 刷新验证码
   */
  refreshCode() {
    const randomStr = randomLenNum(4, true);
    this.form.patchValue({ code: '', randomStr });
    this.codeUrl = `${window.location.origin + window.location.pathname}/cf/code?randomStr=${randomStr}`;
  }

  loginCallBack = (res: any) => {
    const userData = {
      token: res.access_token,
      refreshToken: res.refresh_token,
      expiresIn: res.expires_in,
      scope: res.scope,
      tokenType: res.token_type,
      id: res.user_id,
      name: res.username,
      tenantId: res.tenant_id,
      depId: res.dep_id,
    };

    // 清空路由复用信息
    this.reuseTabService.clear();
    // 设置用户Token信息
    this.tokenService.set(userData);
    this.loading = false;
    // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
    this.startupSrv.load().then(() => {
      this.router.navigate(['/home']);
    });
  };

  ngOnInit(): void {
    this.refreshCode();
  }

  /**
   * 短信验证码
   */
  sendCaptcha(e) {
    this.http.get(`/cf/admin/mobile/login/${this.form2.value.mobile}?_allow_anonymous=true`).subscribe(res => {
      if (res.status !== 200) {
        e.cancel();
      }
    });
  }

  /**
   * 手机号登录
   */
  submit2() {
    this.error = '';
    const data = this.form2.value;

    const grant_type = 'mobile';
    const params = {
      mobile: `SMS@${data.mobile}`,
      code: data.captcha,
      grant_type,
    };

    this.loading = true;
    this.http
      .post(`/cf/auth/mobile/token/sms?_allow_anonymous=true`, null, params, {
        headers: this.header,
      })
      .subscribe(this.loginCallBack, err => {
        this.loading = false;
        this.refreshCode();
      });
  }

  /**
   * 账号密码登录
   */
  submit() {
    this.error = '';
    const data = this.form.value;
    const user = encryption({
      data,
      key: 'cloudframeworker',
      param: ['password'],
    });
    const grant_type = 'password';
    const scope = 'server';
    const params = {
      username: user.username,
      password: encodeURIComponent(user.password),
      randomStr: data.randomStr,
      code: data.code,
      grant_type,
      scope,
    };

    this.loading = true;
    this.http
      .post(`/cf/auth/oauth/token?_allow_anonymous=true`, null, params, {
        headers: this.header,
      })
      .subscribe(this.loginCallBack, err => {
        this.loading = false;
        this.refreshCode();
      });
  }
}
